var mysql = require('mysql');
var connection = mysql.createConnection({
    host: '123.207.219.13',
    user: 'front',
    port:'3306',
    password: 'hfnDiBFX68w3TSm7',
    database: 'front',
    connectTimeout: 60000000
});

connection.connect(err=>{
    console.log(err)
    if(!err){
        console.log('数据库链接成功')
    }
});
//查询数据库表 传入参数 数据库表名
let queryTable = (tableName)=>{
   return new Promise(a=>{
       connection.query('SELECT * FROM '+tableName, function (error, results) {
           if (error) throw error;
           a(results)
       })
   })
}
//查询表 根据条件
let queryTableByParams = (tableName,params)=>{
    console.log(tableName,params)
    // `SELECT * FROM user_list WHERE username='${username}' AND password='${password}'`;
    let arr = []
    for (const key in params) {
        console.log(key)
        arr.push(  `${key}='${params[key]}'`  )
    }
    console.log(arr)
    let sql = `SELECT * FROM ${tableName} WHERE ` + arr.join(' AND ')+';'
    console.log(sql)
    return new Promise(a=>{
        connection.query(sql, function (error, results) {
            if (error) throw error;
            a(results)
        })
    })
}
//自定义mysql语句  传入参数 sql
let customQuery = (sql)=>{
    return new Promise((a,b)=>{
        connection.query(sql, function (error, results) {
            if (error) b(error) ;
            a(results)
        })
    })
}



module.exports = {queryTable,customQuery,queryTableByParams,connection};
